package com.aizhixin.lab.company.service;

import lombok.extern.slf4j.Slf4j;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.core.UserInforCore;
import com.aizhixin.lab.common.domain.PageDomain;
import com.aizhixin.lab.common.dto.SortDTO;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.company.domain.ClassesDomain;
import com.aizhixin.lab.company.domain.LogDomain;
import com.aizhixin.lab.company.domain.OrganDomain;
import com.aizhixin.lab.company.domain.QueryLogDomain;
import com.aizhixin.lab.company.entity.Log;
import com.aizhixin.lab.company.entity.User;
import com.aizhixin.lab.company.repository.LogRepository;

@Slf4j
@Service
@Transactional
public class LogService {
	@Autowired
	private LogRepository logRepository;
	@Autowired
	private PageJdbcUtil pageJdbcUtil; 

	public Map<String, Object> save(LogDomain domain) {
		Map<String, Object> result = new HashMap<>();
		if("登出".equals(domain.getOperationType())){
			updateLastTime(domain.getUserId());
		}
		Log log = new Log();
		log.setCreatedBy(domain.getUserId());
		log.setOperationType(domain.getOperationType());
		log.setOperationTime(new Date());
		logRepository.save(log);
		result.put(ApiReturnConstants.SUCCESS, true);

		return result;
	}
	public Long save(Long createBy){
		Log log = new Log();
		log.setCreatedBy(createBy);
		log.setOperationType("登录");
		log.setOperationTime(new Date());
		logRepository.save(log);
		return log.getId();
	}
	public Long update(Long id){
		Log log = logRepository.findOne(id);
		log.setLastModifiedDate(new Date());
		logRepository.save(log);
		return log.getId();
	}
	public void updateLastTime(Long userId){
		List<Log> logList = logRepository.findByCreatedByAndOperationTypeAndDeleteFlagOrderByCreatedDateDesc(userId,"登录", DataValidity.VALID.getState());
		if (logList.size()>0){
			Log log = logList.get(0);
			log.setLastModifiedDate(new Date());
			logRepository.save(log);
		}
	}
	
	public Map<String, Object> deleteAll(ArrayList<Long> ids) {
        Map<String, Object> result = new HashMap<>();
        logRepository.deleteByIdIn(ids);
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }
	
	 RowMapper<LogDomain> rm = new RowMapper<LogDomain>() {

			@Override
			public LogDomain mapRow(ResultSet rs, int rowNum)
					throws SQLException {
				// TODO Auto-generated method stub
				LogDomain domain = new LogDomain();
				domain.setId(rs.getLong("ID"));
				domain.setUserId(rs.getLong("user_id"));
				domain.setUserName(rs.getString("NAME"));
				domain.setOperationType(rs.getString("OPERATION_TYPE"));
				domain.setOperationTime(rs.getTimestamp("OPERATION_TIME"));
				domain.setCreatedDate(rs.getTimestamp("CREATED_DATE"));
				return domain;
			}
		};
	    
	    public <T> Map<String, Object> findPage(QueryLogDomain domain) {

			String querySql = "select l.id,u.id as user_id,u.`name`,l.OPERATION_TYPE,l.OPERATION_TIME,l.created_date from `t_log` l LEFT JOIN `t_user` u ON l.created_by = u.id where 1=1 ";
			String countSql = "select count(*) FROM `t_log` l LEFT JOIN `t_user` u ON l.created_by = u.id where 1=1 ";
			if (!StringUtils.isEmpty(domain.getUserName())) {
				querySql += " and u.NAME like '%" + domain.getUserName() + "%'";
				countSql += " and u.NAME like '%" + domain.getUserName() + "%'";
			}
			if (!StringUtils.isEmpty(domain.getBeginTime())) {
				querySql += " and l.created_date >='" + domain.getBeginTime() + " 00:00:00'";
				countSql += " and l.created_date >='" + domain.getBeginTime() + " 00:00:00'";
			}
			if (!StringUtils.isEmpty(domain.getEndTime())) {
				querySql += " and l.created_date <='" + domain.getEndTime() + " 23:59:59'";
				countSql += " and l.created_date <='" + domain.getEndTime() + " 23:59:59'";
			}
			List<SortDTO> sort = new ArrayList<SortDTO>();
			SortDTO dto = new SortDTO();
			dto = new SortDTO();
			dto.setKey("l.ID");
			dto.setAsc(false);
			sort.add(dto);

			return pageJdbcUtil.getPageInfor(domain.getPageSize(),
					domain.getPageNumber(), rm, sort, querySql, countSql);
		}
	
}
